using System;
using System.Text.RegularExpressions;

namespace ConfigManager.Core
{
    public class Interpreter
    {
        public static bool Eval(string expression)
        {
            if (expression == null)
                throw new Exception("Invalid format");

            expression = expression.Trim();
            if (expression.StartsWith("\"") && expression.EndsWith("\""))
                expression = expression.Substring(1, expression.Length - 2);

            if (expression.Contains("=="))
            {
                string[] args = Interpreter.Split(expression, "==", true);
                if (args.Length != 2)
                    throw new Exception("Invalid format");
                return (args[0] == args[1]);
            }
            else if (expression.Contains("!="))
            {
                string[] args = Interpreter.Split(expression, "!=", true);
                if (args.Length != 2)
                    throw new Exception("Invalid format");
                return (args[0] != args[1]);
            }
            else
            {
                throw new Exception("Invalid format");
            }
        }


        public static string[] Split(string input, string delimiter, bool ignoreCase)
        {
            string pattern = String.Format("{0}(?=(?:[^{1}]*{1}[^{1}]*{1})*(?![^{1}]*{1}))", 
                        Regex.Escape(delimiter), Regex.Escape("\""));

            RegexOptions options = RegexOptions.Compiled | RegexOptions.Multiline;
            if (ignoreCase) options = options | RegexOptions.IgnoreCase;

            return Regex.Split(input, pattern, options);
        }

        public static bool TrySplitKeyPair(string str, ref string key, ref string value)
        {
            string[] split = Split(str, "=", true);
            if (split.Length != 2)
                return false;

            key = split[0].Trim();
             value = split[1].Trim();
             if (value.StartsWith("\"") && value.EndsWith("\""))
                 value = value.Substring(1, value.Length - 2);
   
            return true;
        }
    
        public static string StripQuotes(string value)
        {
            if (value.StartsWith("\"") && value.EndsWith("\""))
                return value.Substring(1, value.Length - 2);
            else
                return value;
        }

    }
}
